package com.zhouheng.module.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.zhouheng.common.constant.Constants;
import com.zhouheng.common.constant.MenuConstants;
import com.zhouheng.common.exception.BaseException;
import com.zhouheng.module.dao.SysUserMapper;
import com.zhouheng.module.entity.SysUser;
import org.springframework.security.access.annotation.Secured;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * 用户控制层
 * 跳过了server层，以及简单的参数校验
 *
 * @author 周恒
 * @date 20180831 16:28:52
 * @since v1.0
 */
@RestController
@RequestMapping("/user")
public class SysUserController {

    /**
     * sysUserMapper 系统用户dao
     */
    private SysUserMapper sysUserMapper;

    /**
     * captchaProducer 验证码
     */
    private DefaultKaptcha captchaProducer;

    public SysUserController(SysUserMapper sysUserMapper, DefaultKaptcha captchaProducer) {
        this.sysUserMapper = sysUserMapper;
        this.captchaProducer = captchaProducer;
    }

    /**
     * 获取验证码，验证码字符保存到session中，验证码图片返回给前端
     *
     * @param httpServletResponse 描述此参数
     * @param session             描述此参数
     * @throws Exception 描述抛出异常原因
     * @author 周恒
     * @date 20200121 14:16:41
     * @since v1.0
     */
    @GetMapping("/captcha")
    public void defaultKaptcha(HttpServletResponse httpServletResponse, HttpSession session) throws Exception {
        byte[] captchaChallengeAsJpeg;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = captchaProducer.createText();
            session.setAttribute(Constants.SESSION_CAPTCHA, createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = captchaProducer.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(captchaChallengeAsJpeg);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 获取所有用户
     *
     * @return 返回 map 描述此返回参数
     * @author 周恒
     * @date 20180831 16:29:58
     * @since v1.0
     */
    @Secured({MenuConstants.USER_MANAGEMENT})
    @GetMapping("/queryAll")
    public List<SysUser> queryAll() {
        return sysUserMapper.findAll();
    }

    /**
     * 根据id获取指定用户
     *
     * @param id 描述此参数
     * @return 返回 user 描述此返回参数
     * @author 周恒
     * @date 20180903 17:42:28
     * @since v1.0
     */
    @Secured({MenuConstants.USER_MANAGEMENT})
    @GetMapping("/queryById")
    public SysUser queryById(Integer id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据姓名获取用户信息
     *
     * @param userName 描述此参数
     * @return 返回 user 描述此返回参数
     * @author 周恒
     * @date 20180903 17:41:18
     * @since v1.0
     */
    @Secured({MenuConstants.USER_MANAGEMENT})
    @GetMapping("/queryByUserName")
    public SysUser queryByUserName(String userName) {
        return sysUserMapper.findByUsername(userName);
    }

    /**
     * 用户注册
     *
     * @param user 描述此参数
     * @return 返回 user 描述此返回参数
     * @author 周恒
     * @date 20180831 16:30:38
     * @since v1.0
     */
    @PostMapping("/signUp")
    public SysUser signUp(@RequestBody SysUser user) {
        SysUser sysUser = sysUserMapper.findByUsername(user.getUsername());
        if (null != sysUser) {
            throw new BaseException("用户已经存在");
        }
        //密码加密并保存返回用户信息
        user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword()).getBytes()));
        sysUserMapper.insertSelective(user);
        return user;
    }

}
